<template>
  <div class="retailer-confirm-container">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回主页
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>下游企业进场确认</h1>
          <p>处理待确认的零售商产品批号</p>
        </div>

        <!-- 搜索表单 -->
        <el-card class="search-card" shadow="hover">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="零售商名称">
              <el-input 
                v-model="searchForm.retailerName" 
                placeholder="请输入零售商名称" 
                class="search-input"
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                @click="loadRetailerBatches" 
                :loading="loading"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
                查找
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 批号列表 -->
        <div class="batch-list">
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div v-else-if="retailerBatches.length === 0" class="empty-container">
            <el-empty description="暂无待确认的零售商入场请求" />
          </div>

          <div v-else class="batch-cards">
            <el-card
              v-for="batch in retailerBatches"
              :key="batch.rbId"
              class="batch-card"
              shadow="hover"
            >
              <template #header>
                <div class="card-header">
                  <span class="batch-id">批号: {{ batch.batchId }}</span>
                  <el-tag
                    :type="formatStateTag(batch.state)"
                    class="status-tag"
                  >
                    {{ formatState(batch.state) }}
                  </el-tag>
                </div>
              </template>

              <div class="batch-info">
                <div class="info-item">
                  <span class="label">零售商名称:</span>
                  <span class="value">{{ batch.retailerName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">进场时间:</span>
                  <span class="value">{{ batch.createTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品类型:</span>
                  <span class="value">{{ batch.productType }}</span>
                </div>
                <div class="info-item">
                  <span class="label">产品品种:</span>
                  <span class="value">{{ batch.productVariety }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                  type="success"
                  size="small"
                  @click="handleConfirm(batch.rbId)"
                  :disabled="batch.state !== 2"
                  class="action-btn"
                >
                  <el-icon><Check /></el-icon>
                  确认
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="viewDetails(batch)"
                  class="action-btn"
                >
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          :current-page="pageInfo.pageNum"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next"
          style="margin-top: 30px; text-align: right;"
          :disabled="loading"
          background
        />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Search,
  Loading,
  Check,
  View
} from '@element-plus/icons-vue'
import { 
  getRetailerConfirmListService,
  confirmRetailerBatchService
} from '@/api/wholesaler'

const router = useRouter()

// 搜索表单
const searchForm = ref({
  retailerName: ''
})

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 零售商批次列表
const retailerBatches = ref([])

// 格式化状态显示
const formatState = (state) => {
  const stateMap = {
    1: '新建',
    2: '待确认',
    3: '已确认',
    4: '已下架'
  }
  return stateMap[state] || '未知'
}

// 格式化状态标签类型
const formatStateTag = (state) => {
  const typeMap = {
    1: 'primary',
    2: 'warning',
    3: 'success',
    4: 'info'
  }
  return typeMap[state] || 'info'
}

// 返回主页
const goBack = () => {
  router.push('/ent/farm')
}

// 加载列表数据
const loadRetailerBatches = async () => {
  loading.value = true
  try {
    const res = await getRetailerConfirmListService({
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      retailerName: searchForm.value.retailerName
    })
    retailerBatches.value = res.data.records || []
    pageInfo.value.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))
    retailerBatches.value = []
    pageInfo.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理确认
const handleConfirm = async (rbId) => {
  ElMessageBox.confirm(
    '确定要确认该进场请求吗？',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'confirm-btn'
    }
  ).then(async () => {
    try {
      await confirmRetailerBatchService(rbId)
      ElMessage.success('确认成功')
      loadRetailerBatches()
    } catch (error) {
      ElMessage.error('确认失败: ' + (error.message || '未知错误'))
    }
  })
}

// 查看详情
const viewDetails = (batch) => {
  ElMessageBox.alert(
    `
      <div style="text-align: left; line-height: 1.8;">
        <p><strong>产品批号:</strong> ${batch.batchId || "-"}</p>
        <p><strong>零售商名称:</strong> ${batch.retailerName || "-"}</p>
        <p><strong>进场时间:</strong> ${batch.createTime || "-"}</p>
        <p><strong>产品类型:</strong> ${batch.productType || "-"}</p>
        <p><strong>产品品种:</strong> ${batch.productVariety || "-"}</p>
        <p><strong>状态:</strong> ${formatState(batch.state)}</p>
      </div>
    `,
    "零售商产品批号详情",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      customClass: "detail-dialog"
    }
  )
}

// 分页变化
const handlePageChange = (pageNum) => {
  pageInfo.value.pageNum = pageNum
  loadRetailerBatches()
}

const handleSizeChange = (pageSize) => {
  pageInfo.value.pageSize = pageSize
  pageInfo.value.pageNum = 1
  loadRetailerBatches()
}

// 初始化
onMounted(() => {
  loadRetailerBatches()
})
</script>

<style scoped>
.retailer-confirm-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.back-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-btn .el-icon {
  margin-right: 8px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #718096;
  font-size: 16px;
}

.search-card {
  margin-bottom: 30px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.search-form {
  padding: 20px 0;
}

.search-input {
  width: 250px;
}

.search-btn {
  border-radius: 6px;
}

.search-btn .el-icon {
  margin-right: 6px;
}

.batch-list {
  min-height: 400px;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #718096;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.batch-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.batch-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s ease;
}

.batch-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-id {
  font-weight: 600;
  color: #2d3748;
}

.status-tag {
  font-weight: 500;
}

.batch-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #718096;
  font-size: 14px;
  font-weight: 500;
}

.value {
  color: #2d3748;
  font-size: 14px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

.action-btn .el-icon {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .search-input {
    width: 180px;
  }

  .batch-cards {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .action-buttons {
    justify-content: center;
  }
}
</style>

<style>
.confirm-btn {
  background-color: #67c23a;
  border-color: #67c23a;
}

.confirm-btn:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

.detail-dialog {
  min-width: 500px;
}
</style>